const { getList, getDetail, insertBlog, updateBlog, deleteBlog } = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { filterKey } = require('../utils/func')

const handleBlogRouter = (req, res) => {
  const method = req.method
  const { id } = req.query || {}
  const columnNames = ['title', 'content']

  // 获取博客列表
  if (method === 'GET' && req.path === '/api/blog/list') {
    const { author } = req.query || {}
    const { keyword } = req.query || {}
    const result = getList(author, keyword)

    return result.then(listData => {
      return new SuccessModel(listData)
    })
  }

  // 获取博客详情
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const blogResult = getDetail(id)
    // return blogResult.then(data => {
    //   return new SuccessModel(data)
    // })
    // or
    return blogResult.then(row => {
      return new SuccessModel(row[0])
    })
  }

  // 新增一篇博客
  if (method === 'POST' && req.path === '/api/blog/insert') {
    const blogData = req.body
    const flag = filterKey(blogData, columnNames)
    if (flag) {
      blogData.author = 'zhangsan'
      const result = insertBlog(blogData)
      return result.then(data => {
        return new SuccessModel(data)
      })
    } else {
      return new Promise((reslove, reject) => {
        reslove('新增失败')
      }).then(data => {
        return new ErrorModel(data)
      })
    }
  }

  // 更新一篇博客
  if (method === 'POST' && req.path === '/api/blog/update') {
    const blogData = req.body
    const flag = filterKey(blogData, columnNames)
    if (flag) {
      const result = updateBlog(id, blogData)
      return result.then(data => {
        if (data) {
          return new SuccessModel()
        } else {
          return new ErrorModel('更新失败')
        }
      })
    } else {
      return new Promise((reslove, reject) => {
        reslove('参数异常')
      }).then(data => {
        return new ErrorModel(data)
      })
    }
  }

  // 删除一篇博客(软删除)
  if (method === 'POST' && req.path === '/api/blog/delete') {
    const { author } = req.body
    if (author && id) {
      const result = deleteBlog(id, author)
      return result.then(data => {
        if (data) {
          return new SuccessModel()
        } else {
          return new ErrorModel('删除失败')
        }
      })
    } else {
      return new Promise((reslove, reject) => {
        reslove('参数异常')
      }).then(data => {
        return new ErrorModel(data)
      })
    }
  }
}

module.exports = handleBlogRouter
